<template>
  <div>
    <el-dialog
        :close-on-click-modal="false"
        title="事件详情"
        :visible.sync="dialogVisible"
        height="440px"
        width="800px"
        class="re-dialog"
    >
        <div class="taaept-box">
        <el-form :model="ruleForm" :rules="rules" ref="ruleForm">
            <el-form-item label="事件名称：" :label-width="formLabelWidth" prop="eventName">
            <el-input readonly placeholder="名称" v-model="record.eventName"></el-input>
            </el-form-item>
            <el-form-item label="事件地点：" :label-width="formLabelWidth" prop="eventAddress">
            <el-input type="textarea" readonly placeholder="地点" v-model="record.eventAddress"></el-input>
            </el-form-item>
            <el-form-item
            :label="item.label"
            :label-width="formLabelWidth"
            :prop="item.code"
            v-for="(item,index) in listCofig"
            :key="index"
            >
            <el-select
                v-if="item.type === 'select'"
                :disabled="item.disabled"
                style="width:100%"
                v-model="record[item.code]"
                placeholder="请选择"
            >
                <el-option
                v-for="(it,ind) in item.data"
                :key="ind"
                v-bind:label="it.dictDataName"
                v-bind:value="it.dictDataCode"
                ></el-option>
            </el-select>
            <el-cascader
                :disabled="item.disabled"
                v-else-if="item.type === 'cascader'"
                v-model="ruleForm[item.code]"
                :props="{ label: 'dictDataName',value: 'dictDataCode' }"
                :placeholder="item.placeholder"
                :options="item.data"
                style="width: 100%"
            ></el-cascader>
            <el-tag
                v-else-if="item.type === 'tag'"
                class="tag"
                v-for="(it,ind) in item.data"
                :key="ind"
                size="mini"
                @click="tagClik(it,item.code)"
                :disable-transitions="true"
                :hit="true"
                :style="(ruleForm[item.code]===it.dictDataCode)?`background-color:${it.dictDataDesc};color:#fff`:`color:${it.dictDataDesc};border:1px solid ${it.dictDataDesc}`"
            >{{it.dictDataName}}</el-tag>
            </el-form-item>
            <el-form-item label="事件描述：" :label-width="formLabelWidth" prop="eventDetail">
            <el-input type="textarea" readonly placeholder="事件描述" v-model="record.eventDetail"></el-input>
            </el-form-item>
            <el-form-item
            label="限期办结时间："
            :label-width="formLabelWidth"
            >{{getTimeStr(record.dueTime) || ""}}</el-form-item>
            <el-form-item label="问题来源：" :label-width="formLabelWidth" prop="eventSourceName">
            <el-input readonly placeholder="来源" v-model="record.eventSourceName"></el-input>
            </el-form-item>
            <el-form-item label="接收者：" :label-width="formLabelWidth" prop="receiverId" v-if="isPf()">
            <el-select style="width:100%" v-model="ruleForm.receiverId" placeholder="请选择接收者">
                <el-option
                v-for="(it,ind) in receiverIdList"
                :key="ind"
                v-bind:label="it.dictDataName"
                v-bind:value="it.dictDataCode"
                ></el-option>
            </el-select>
            </el-form-item>
            <el-form-item
            label="处理意见："
            :label-width="formLabelWidth"
            prop="opinion"
            v-if="btnType&&btnType.length>0"
            >
            <el-input type="textarea" placeholder="请输入意见" v-model="ruleForm.opinion" :maxlength="1000"></el-input>
            </el-form-item>
        </el-form>
        <div class="time-line-parent">
            <Timeline :list="eventList" :title="record.eventName" >
                <div class="m-l-20" slot = "titleButton">
                    <el-button size = "mini" type = "primary" @click = "onHistory">历史处置情况</el-button>
                </div>
            </Timeline>
        </div>
        </div>
        <span slot="footer" class="dialog-footer">
        <el-button
            v-for="(item,index) in btnList"
            :key="index"
            type="success"
            @click="submitForm('ruleForm',item.type)"
            size="small"
            :style="`background-color:${item.color}; border-color:transparent`"
            v-if="btnType.indexOf('all')>-1||btnType.indexOf(item.type)>-1"
        >{{item.name}}</el-button>
        </span>
    </el-dialog>
    <el-dialog 
        title="历史处置情况"
        :visible="historyVisible"
        @close = "historyVisible = false"
    >
        <div class="history-wrapper">
            <Timeline :list="historyEventList" :title="record.eventName" >
            </Timeline>
        </div>
    </el-dialog>
  </div>
</template>

<script>
import Pubsub from "../../utils/pubsub";
import { getTimeStr } from "../../utils/index";
import Timeline from "../common/Timeline";
import {
  eventInfoCenterReceive,
  eventInfoCenterDistribute,
  eventInfoPress,
  eventInfoCenterEnd,
  findByDictCode,
  dictItemQueryEventTypeCodeTree,
  getRolePeople,
  eventInfoCenterReport,
  eventHandleFlowFindByEventId,
  queryHistory
} from "../../config/api";
export default {
  components: {
    Timeline
  },
  props: {
    // list: Array
  },
  data() {
    return {
      record: {},
      btnType: ["all"], //事件管理传过来的，用于显示什么按钮
      source: "", //哪里点进来的
      formLabelWidth: "100px",
      dialogVisible: false,
      getTimeStr,
      ruleForm: {
        eventName: "",
        classBigCode: "",
        classSmallCode: "",
        eventLevelCode: "", //事件等级
        emergencyCode: "", //紧急程度
        eventAddress: "",
        receiverId: "",
        opinion: ""
      },
      rules: {
        classCode: [
          {
            required: true,
            message: "请选择类别",
            trigger: ["blur", "change"]
          }
        ],
        // classBigCode: [
        //     {
        //         required: true,
        //         message: "请选择大类",
        //         trigger: ["blur", "change"]
        //     }
        // ],
        // classSmallCode: [
        //     {
        //         required: true,
        //         message: "请选择小类",
        //         trigger: ["blur", "change"]
        //     }
        // ],
        eventLevelCode: [
          {
            required: true,
            message: "请选择事件等级",
            trigger: ["blur", "change"]
          }
        ],
        emergencyCode: [
          {
            required: true,
            message: "请选择紧急程度",
            trigger: ["blur", "change"]
          }
        ],
        opinion: [
          {
            required: true,
            message: "请输入处理意见",
            trigger: ["blur", "change"]
          }
        ]
      },
      sourceCodeList: [],
      eventList: [],
      listCofig: [
        {
          label: "事件类型：",
          value: "",
          code: "classCode",
          type: "cascader",
          placeholder: "请选择事件类型",
          disabled: true,
          data: []
        },
        {
          label: "事件等级：",
          value: "",
          code: "eventLevelCode",
          type: "tag",
          disabled: true,
          data: []
        },
        {
          label: "紧急程度：",
          value: "",
          code: "emergencyCode",
          type: "tag",
          disabled: true,
          data: []
        }
        // {
        //     label: "事件类型：",
        //     value: "",
        //     code: "classBigCode",
        //     type: "select",
        //     disabled: true,
        //     data: []
        // },
        // {
        //     label: "事件小类：",
        //     value: "",
        //     code: "classSmallCode",
        //     type: "select",
        //     disabled: true,
        //     data: []
        // },
      ],
      btnList: [
        { type: "sl", color: "#1a36a9", name: "受理" },
        { type: "pf", color: "#2b88ff", name: "派发" },
        { type: "db", color: "#2b88ff", name: "督办" },
        { type: "ja", color: "#1cca82", name: "结案" },
        { type: "sb", color: "#2b88ff", name: "上报" }
      ],
      receiverIdList: [],
      historyVisible:false,//历史处置情况弹窗
      historyEventList:[],//历史处置情况列表
    };
  },
  mounted() {
    this.pubsub_token = Pubsub.subscribe("ProcessingDialog", (type, values) => {
      console.log("values", values);
      const { btnType = ["all"], item = {}, source = "" } = values;
      const { listCofig } = this;
      setTimeout(() => {
        this.$refs.ruleForm.clearValidate(); //重置
      }, 0);
      if (item) {
        this.ruleForm = {
          eventName: item.eventName,
          eventAddress: item.eventName,
          opinion: item.opinion,
          receiverId: item.receiverId,
          receiverName: item.receiverName,
          classCode: [item.classBigCode, item.classSmallCode],
          eventLevelCode: item.eventLevelCode, //事件等级
          emergencyCode: item.emergencyCode //紧急程度
        }; //重置
        console.log("this.ruleForm", this.ruleForm);
        if (item.classBigCode == null || item.classSmallCode == null) {
          listCofig[0].disabled = false;
        } else {
          listCofig[0].disabled = true;
        }
        if (!item.eventLevelCode && item.eventLevelCode != 0) {
          listCofig[1].disabled = false;
        } else {
          listCofig[1].disabled = true;
        }
        if (!item.emergencyCode && item.emergencyCode != 0) {
          listCofig[2].disabled = false;
        } else {
          listCofig[2].disabled = true;
        }
        this.dialogVisible = true;
        this.record = item || {};
        this.btnType = btnType;
        this.rules.opinion[0].required = btnType && btnType.length > 0;
        this.source = source;
        // this.listCofig.find(item => item.code == "classBigCode").data = [
        //   {
        //     dictDataName: item.classBigName,
        //     dictDataCode: item.classBigCode
        //   }
        // ];
        //当是派发时候就添加接收人
        if (btnType.indexOf("pf") > -1) {
          this.getPf();
        }
        this.findByEventId({ eventId: item.id });
      } else {
        this.ruleForm = {};
      }
    });
    this.getDictCode();
  },
  destroyed() {
    this.pubsub_token && Pubsub.unsubscribe(this.pubsub_token);
  },
  methods: {
      /**
       * 历史处置情况
       */
      onHistory(){
          this.historyVisible = true;
          let {eventNumber} = this.record;
          queryHistory({eventNumber}).then((result = {})=>{
              let {eventFlowData = [],sysAttrFiles = []} = result.data[0] || {};
              eventFlowData[0].sysAttrFiles = sysAttrFiles;
              this.historyEventList = eventFlowData;
              console.log(eventFlowData,"sss")

          })
      },
    isPf() {
      const { btnType } = this;
      return btnType.includes("pf");
    },
    codeToName(code = "", codeName = "", obj = {}, list = []) {
      //通过code设置name
      console.log(code,codeName,obj,list);
      if (list && list.length) {
        obj[codeName] = (list.find( item => item.dictDataCode == obj[code] )||{}).dictDataName;
      }
    },
    /**
     * 获取数据字典--取件类型
     */
    getDictCode() {
      //事件等级
      findByDictCode({ dictCode: "eventLevelCode" }).then((res = {}) => {
        console.log("asdres ", res);
        this.listCofig.find(item => item.code == "eventLevelCode").data =
          res.data || [];
      });
      //紧急程度
      findByDictCode({ dictCode: "emergencyCode" }).then((res = {}) => {
        this.listCofig.find(item => item.code == "emergencyCode").data =
          res.data || [];
      });
      // //事件类型
      // findByDictCode({ dictCode: "classBigCode" }).then((res = {}) => {
      //     this.listCofig.find(item => item.code == "classBigCode").data =
      //         res.data || [];
      // });
      // //事件小类
      // findByDictCode({ dictCode: "classSmallCode" }).then((res = {}) => {
      //     this.listCofig.find(
      //         item => item.code == "classSmallCode"
      //     ).data = res.data || [];
      // });

      //事件类型
      dictItemQueryEventTypeCodeTree().then((res = {}) => {
        let data = res.data || [];
        data.map(item => {
          let firstChildren = item.children || [];
          firstChildren.map(it => {
            delete it.children;
          });
        });
        this.listCofig[0].data = data;
      });
    },
    //派发接收者
    getPf() {
      getRolePeople({ roleType: "ky" }).then((res = {}) => {
        if (res.data && res.data.length) {
          res.data.map(item => {
            item.dictDataName = item.name;
            item.dictDataCode = item.id;
          });
          this.receiverIdList = res.data || [];
        }
      });
    },
    /**
     * 查询事件流水
     */
    findByEventId(eventId) {
      //城管pc端工作台查询所有事件
      eventHandleFlowFindByEventId({ ...eventId, type: "pc" }).then(
        (res = {}) => {
          this.eventList = res.data;
        }
      );
    },
    /**
     * 点击tag标签事件
     */
    tagClik(item, code) {
      if (this.record[code] || this.record[code] == 0) {
        return;
      }
      this.ruleForm[code] = item.dictDataCode;
      console.log("tagClik", this.ruleForm);
    },
    submitForm(formName, type) {
      this.$refs[formName].validate((valid, values) => {
        const { record, ruleForm, source } = this;
        console.log("ruleForm", ruleForm);
        if (valid) {
          if (type == "sl") {
            //受理
            let classCode = this.ruleForm.classCode;
            if (classCode && classCode.length) {
              this.ruleForm.classBigCode = classCode[0];
              this.ruleForm.classSmallCode = classCode[1];
            this.codeToName(
              "classBigCode",
              "classBigName",
              this.ruleForm,
              this.listCofig[0].data
            );
            this.codeToName(
              "classSmallCode",
              "classSmallName",
              this.ruleForm,
              (this.listCofig[0].data||{}).find(item=>item.dictDataCode==classCode[0]).children||{}
            );
            } else {
              this.ruleForm.classBigCode = "";
              this.ruleForm.classBigName= "";
              this.ruleForm.classSmallCode = "";
              this.ruleForm.classSmallName = "";
            }
            this.codeToName(
              "eventLevelCode",
              "eventLevelName",
              this.ruleForm,
              this.listCofig[1].data
            );
            this.codeToName(
              "emergencyCode",
              "emergencyName",
              this.ruleForm,
              this.listCofig[2].data
            );
            eventInfoCenterReceive({
              id: record.id,
              ...this.ruleForm
            }).then(res => {
              this.$message({
                message: "受理成功",
                type: "success"
              });
              this.dialogVisible = false;
              if (source == "xxzx") {
                Pubsub.publish("WORKBENCH_MESSAGE_CENTER");
              } else {
                this.$emit("callBack");
              }
            });
          } else if (type == "pf") {
            //派发
            if (!ruleForm.receiverId) {
              this.$message({
                message: "派发请添加接收者",
                type: "warning"
              });
              return;
            }
            this.codeToName(
              "receiverId",
              "receiverName",
              this.ruleForm,
              this.receiverIdList
            );
            eventInfoCenterDistribute({
              id: record.id,
              opinion: ruleForm.opinion,
              receiverId: ruleForm.receiverId,
              receiverName: ruleForm.receiverName
            }).then(res => {
              this.$message({
                message: "派发成功",
                type: "success"
              });
              this.dialogVisible = false;
              if (source == "xxzx") {
                Pubsub.publish("WORKBENCH_MESSAGE_CENTER");
              } else {
                this.$emit("callBack");
              }
            });
          } else if (type == "db") {
            //督办
            eventInfoPress({
              id: record.id,
              opinion: ruleForm.opinion
            }).then(res => {
              this.$message({
                message: "督办成功",
                type: "success"
              });
              this.dialogVisible = false;
              if (source == "xxzx") {
                Pubsub.publish("WORKBENCH_MESSAGE_CENTER");
              } else {
                this.$emit("callBack");
              }
            });
          } else if (type == "ja") {
            //结案
            eventInfoCenterEnd({
              id: record.id,
              opinion: ruleForm.opinion
            }).then(res => {
              this.dialogVisible = false;
              this.$message({
                message: "结案完成",
                type: "success"
              });
              this.$emit("callBack");
            });
          } else if (type == "sb") {
            //上报
            eventInfoCenterReport({
              id: record.id,
              opinion: ruleForm.opinion
            }).then(res => {
              this.dialogVisible = false;
              this.$message({
                message: "上报完成",
                type: "success"
              });
              this.$emit("callBack");
            });
          }
        }
      });
    }
  }
};
</script>

<style lang = "scss" scoped>
.taaept-box {
  display: flex;
  flex-direction: row;
  > * {
    flex: 1;
    padding-left: 20px;
  }
}
.dialog-footer {
  margin-top: 0;
}
.time-line-parent {
  max-height: 497px;
  overflow-y: auto;
}
.tag {
  color: #333;
  cursor: pointer;
  margin-right: 10px;
  background-color: #fff;
  border: 1px solid transparent;
  &:active {
    opacity: 0.8;
  }
}
.m-l-20{
    margin-left: 20px;
}
.history-wrapper{
    max-height: 70vh;
    overflow: auto;
}
</style>